using System.Collections;
using UnityEngine;

public class AsteroidController : MonoBehaviour
{
    [SerializeField] private float movementSpeed = 3f;
    [SerializeField] private float rotationSpeed = 20f;
    [SerializeField] private GameObject littleAsteroid;
    
    private GameManager gameManager;
    private PlayerController player;

    private Vector3 randomDirection;
    private Vector3 randomRotation;
    
    void Start()
    {
        gameManager = GameObject.FindGameObjectWithTag("GameController").GetComponent<GameManager>();
        player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();
        randomDirection = RandomDirection();
        randomRotation = RandomRotation();
        StartCoroutine(LifeEnd());
    }

    
    void Update()
    {
        transform.Translate(randomDirection * (movementSpeed * Time.deltaTime), Space.World);
        transform.Rotate(randomRotation * (rotationSpeed * Time.deltaTime));
    }
    
    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            if (!player.isShield)
            {
                gameManager.RemoveLife(1);
            }
            
            DestroySelf();
        }
        else if (other.CompareTag("Bullet"))
        {
            if (CompareTag("Asteroid"))
            {
                gameManager.UpdateScore(20);
            }
            
            else if (CompareTag("LittleAsteroid"))
            {
                gameManager.UpdateScore(10); 
            }
            
            DestroySelf();
            Destroy(other.gameObject);
        }
    }

    private void DestroySelf()
    {
        Destroy(gameObject);
        if (gameObject.CompareTag("Asteroid"))
        {
            CreateLittleAsteroid();
        }
    }

    private void CreateLittleAsteroid()
    {
        int random = Random.Range(1, 5);
        for (int i = 0; i < random; i++)
        {
            //可以尝试编写随机Scale和随机的碰撞体大小
            Instantiate(littleAsteroid, transform.position, littleAsteroid.transform.rotation);
        }
    }

    IEnumerator LifeEnd()
    {
        yield return new WaitForSeconds(15f);
        DestroySelf();
    }
    
    private Vector3 RandomDirection()
    {
        float x = Random.Range(-1f, 1f);
        float y = Random.Range(-1f, 1f);
        return new Vector3(x, y, 0);
    }

    private Vector3 RandomRotation()
    {
        float x = Random.Range(-1f, 1f);
        float y = Random.Range(-1f, 1f);
        float z = Random.Range(-1f, 1f);
        return new Vector3(x, y, z);
    }
}
